package com.zryc.shop.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zryc.shop.feign.IFeignProduct;
import com.zryc.shop.jwt.JWTUtil;
import com.zryc.shop.oms.entity.Order;
import com.zryc.shop.oms.entity.OrderItem;
import com.zryc.shop.oms.entity.OrderOperateHistory;
import com.zryc.shop.oms.entity.OrderReturnApply;
import com.zryc.shop.oms.mapper.OrderMapper;
import com.zryc.shop.oms.service.IOrderItemService;
import com.zryc.shop.oms.service.IOrderOperateHistoryService;
import com.zryc.shop.oms.service.IOrderReturnApplyService;
import com.zryc.shop.oms.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author zhaozhao
 * @since 2024-01-18
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {


    @Autowired
    private IOrderOperateHistoryService orderOperateHistoryService;

    @Autowired
    private IOrderItemService orderItemService;

    @Autowired
    private IOrderReturnApplyService orderReturnApplyService;

    @Autowired
    private IFeignProduct feignProduct;

    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @param orderSn
     * @param receiverKeyword
     * @param status
     * @param orderType
     * @param sourceType
     * @param createTime
     * @return
     */
    @Override
    public Page<Order> list(Integer pageNum, Integer pageSize, String orderSn,
                            String receiverKeyword, Integer status, Integer orderType,
                            Integer sourceType, Date createTime) {
        Page<Order> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(orderSn)) {
            wrapper.like("order_sn", orderSn);
        }
        if (!StringUtils.isEmpty(receiverKeyword)) {
            wrapper.like("receive_keyword", receiverKeyword);
        }

        if (status != null) {
            wrapper.eq("status", status);
        }

        if (orderType != null) {
            wrapper.eq("order_type", orderType);
        }

        if (sourceType != null) {
            wrapper.eq("source_type", sourceType);
        }

        if (createTime != null) {
            // 使用 Calendar 类来操作日期
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(createTime);

            // 设置为给定日期的 00:00:00
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);

            // 获取给定日期的时间戳（00:00:00）
            Date startTime = calendar.getTime();

            // 设置为给定日期的 23:59:59，即该天的最后一秒
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);

            // 获取给定日期的最后一秒的时间戳
            Date endTime = calendar.getTime();

            wrapper.ge("create_time", startTime);
            wrapper.le("create_time", endTime);
        }

        return page(page, wrapper);
    }

    /**
     * 修改备注信息
     *
     * @param id
     * @param status
     * @param note
     * @param token
     * @return
     */
    @Override
    @Transactional
    public Object updateNode(Long id, Integer status, String note, String token) {
        String userinfo = JWTUtil.parse(token.split(" ")[1]);
        String[] info = userinfo.split(",");
        Order order = baseMapper.selectById(id);
        LocalDateTime now = LocalDateTime.now();
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("note", note);
        baseMapper.update(order, updateWrapper);
        OrderOperateHistory orderOperateHistory = new OrderOperateHistory();
        orderOperateHistory.setOrderId(order.getId());
        orderOperateHistory.setOperateMan(info[2]);
        orderOperateHistory.setCreateTime(now);
        orderOperateHistory.setOrderStatus(order.getStatus());
        orderOperateHistory.setNote("修改备注信息:" + note);
        orderOperateHistoryService.save(orderOperateHistory);
        return "修改备注信息成功";
    }

    /**
     * 删除订单
     *
     * @param ids
     * @param token
     * @return
     */
    @Override
    @Transactional
    public Object deleteOrder(String ids, String token) {
        String userinfo = JWTUtil.parse(token.split(" ")[1]);
        String[] info = userinfo.split(",");
        String[] idList = ids.split(",");
        for (String id : idList) {
            Order order = baseMapper.selectById(id);
            if (order.getStatus() == 4 && order.getStatus() == 5) {
                LocalDateTime now = LocalDateTime.now();
                UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
                wrapper.eq("id", id);
                wrapper.set("delete_status", 1);
                order.setModifyTime(now);
                baseMapper.update(order, wrapper);
                OrderOperateHistory orderOperateHistory = new OrderOperateHistory();
                orderOperateHistory.setOrderId(order.getId());
                orderOperateHistory.setOperateMan(info[2]);
                orderOperateHistory.setCreateTime(now);
                orderOperateHistory.setOrderStatus(order.getStatus());
                orderOperateHistory.setNote("删除订单！！！");
                orderOperateHistoryService.save(orderOperateHistory);
            }
        }
        return "删除成功";
    }

    /**
     * 关闭订单
     *
     * @param ids
     * @param note
     * @param token
     * @return
     */
    @Override
    @Transactional
    public Object close(String ids, String note, String token) {
        String userinfo = JWTUtil.parse(token.split(" ")[1]);
        String[] info = userinfo.split(",");
        String[] idList = ids.split(",");
        for (String id : idList) {
            Order order = baseMapper.selectById(id);
            if (order.getStatus() == 0) {
                LocalDateTime now = LocalDateTime.now();
                UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
                wrapper.eq("id", id);
                wrapper.set("status", 4);
                wrapper.set("modify_time", now);
                baseMapper.update(order, wrapper);
                OrderOperateHistory orderOperateHistory = new OrderOperateHistory();
                orderOperateHistory.setOrderId(order.getId());
                orderOperateHistory.setOperateMan(info[2]);
                orderOperateHistory.setCreateTime(now);
                orderOperateHistory.setOrderStatus(order.getStatus());
                if (note == null) {
                    orderOperateHistory.setNote("订单关闭:xxx");
                }
                orderOperateHistory.setNote("订单关闭：" + note);
                orderOperateHistoryService.save(orderOperateHistory);

                List<OrderItem> orderItemList = orderItemService.list(new QueryWrapper<OrderItem>().eq("order_id", id));
                for(OrderItem orderItem : orderItemList){
                    Long productId = orderItem.getProductId();
                    Integer productCount = orderItem.getProductQuantity();
                    if (productId != null) {
                        feignProduct.recieve(productId, productCount);
                        feignProduct.skuStock(productId, productCount);
                    }
                }
            }
        }
        return "关闭成功";
    }

    /**
     * 订单发货
     *
     * @param params
     * @param token
     * @return
     */
    @Override
    @Transactional
    public Object delivery(List<HashMap> params, String token) {
        String userinfo = JWTUtil.parse(token.split(" ")[1]);
        String[] info = userinfo.split(",");
        LocalDateTime now = LocalDateTime.now();
        for (HashMap map : params) {
            Integer orderId = (Integer) map.get("orderId");
            // 根据订单ID获取订单信息
            Order order = baseMapper.selectById(orderId);
            UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", orderId);
            wrapper.set("status", 2);
            wrapper.set("modify_time", now);
            baseMapper.update(order, wrapper);
            OrderOperateHistory orderOperateHistory = new OrderOperateHistory();
            orderOperateHistory.setOrderId(order.getId());
            orderOperateHistory.setOperateMan(info[2]);
            orderOperateHistory.setCreateTime(now);
            orderOperateHistory.setOrderStatus(order.getStatus());
            orderOperateHistory.setNote("完成发货");
            orderOperateHistoryService.save(orderOperateHistory);
        }
        return "发货成功";
    }

    /**
     * 修改订单费用信息
     *
     * @param params
     * @param token
     * @return
     */
    @Override
    @Transactional
    public Object updateMoneyInfo(HashMap params, String token) {
        String userinfo = JWTUtil.parse(token.split(" ")[1]);
        String[] info = userinfo.split(",");
        LocalDateTime now = LocalDateTime.now();
        Integer orderId = (Integer) params.get("orderId");
        // 根据订单ID获取订单信息
        Order order = baseMapper.selectById(orderId);
        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", orderId);
        wrapper.set("modify_time", now);
        baseMapper.update(order, wrapper);
        OrderOperateHistory orderOperateHistory = new OrderOperateHistory();
        orderOperateHistory.setOrderId(order.getId());
        orderOperateHistory.setOperateMan(info[2]);
        orderOperateHistory.setCreateTime(now);
        orderOperateHistory.setOrderStatus(order.getStatus());
        orderOperateHistory.setNote("修改费用信息");
        orderOperateHistoryService.save(orderOperateHistory);
        return "修改订单费用信息成功";
    }

    /**
     * 修改收件人信息
     *
     * @param params
     * @param token
     * @return
     */
    @Override
    @Transactional
    public Object updateReceiverInfo(HashMap params, String token) {
        String userinfo = JWTUtil.parse(token.split(" ")[1]);
        String[] info = userinfo.split(",");
        LocalDateTime now = LocalDateTime.now();
        Integer orderId = (Integer) params.get("orderId");
        // 根据订单ID获取订单信息
        Order order = baseMapper.selectById(orderId);
        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", orderId);
        wrapper.set("modify_time", now);
        baseMapper.update(order, wrapper);
        OrderOperateHistory orderOperateHistory = new OrderOperateHistory();
        orderOperateHistory.setOrderId(order.getId());
        orderOperateHistory.setOperateMan(info[2]);
        orderOperateHistory.setCreateTime(now);
        orderOperateHistory.setOrderStatus(order.getStatus());
        orderOperateHistory.setNote("修改收件人信息");
        orderOperateHistoryService.save(orderOperateHistory);
        return "修改收件人信息成功";
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public Object detail(Long id) {
        Order order = baseMapper.selectById(id);
        //设置操作日志
        QueryWrapper<OrderOperateHistory> orderOperateHistoryQueryWrapper = new QueryWrapper<>();
        orderOperateHistoryQueryWrapper.eq("order_id",id);
        List<OrderOperateHistory> historyList = orderOperateHistoryService.getBaseMapper().selectList(orderOperateHistoryQueryWrapper);
        order.setHistoryList(historyList);
        //设置商品信息
        QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
        orderItemQueryWrapper.eq("order_id",id);
        List<OrderItem> orderItems = orderItemService.getBaseMapper().selectList(orderItemQueryWrapper);
        order.setOrderItemList(orderItems);
        return order;
    }
}
